package com.daqian.cloud.oauth2.authentication;

import com.alibaba.fastjson.JSON;
import com.daqian.chance.core.rest.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义-登录失败处理器
 * @author: daqian
 * @date: 2019/7/2 13:50
 */
@Component
@Slf4j
public class ChanceAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.warn("登录失败");
        //设置状态码
        response.setStatus(500);
        response.setContentType("application/json;charset=UTF-8");
        //将 登录失败 信息打包成json格式返回
        response.getWriter().write(JSON.toJSONString(RestResult.fail(exception.getMessage())));
    }
}
